package org.zebra.web.annotation.sensitive;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.extern.slf4j.Slf4j;
import org.zebra.common.util.SpringElUtil;

import java.io.IOException;
import java.util.Objects;

/**
 * @author zhanghongbin
 */
@Slf4j
public class SpelSensitiveJsonSerializer extends JsonSerializer<Object> implements ContextualSerializer {

    private String el;
    private String name;

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
            throws IOException {
        try {
            o = SpringElUtil.parse(el, SpringElUtil.getStandardEvaluationContext(name, o), Object.class);
        } catch (Exception e) {
            log.error(name + " el 表达式 " + el + "错误", e);
        }
        jsonGenerator.writeObject(o);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty)
            throws JsonMappingException {
        SpelSensitive spelSensitive = beanProperty.getAnnotation(SpelSensitive.class);
        if (Objects.nonNull(spelSensitive) && spelSensitive.value().trim().length() != 0) {
            el = spelSensitive.value();
            this.name = beanProperty.getName();
            return this;
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
    }
}
